﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;
using System.Data.OleDb;
using System.Text.RegularExpressions;

namespace AliCMS.SubscribeModule.OleDb
{
    public partial class Mail : OleDbBase, Dal.IMail
    {
        public int GetInnerIDFromGuid(Guid guid)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.Mail.ID, MapType(Alias.Mail.ID)).Value = guid;
            Command.CommandText = "SELECT " + MapColumn(Alias.Mail.InnerID) + " FROM " + MapTable(Alias.Objects.Mail) + " WHERE " + MapColumn(Alias.Mail.ID) + "=?";
            object result = Command.ExecuteScalar();
            if (result == null)
                return 0;
            else
                return (int)result;
        }
        public Guid GetGuidFromInnerID(object id)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.Mail.InnerID, MapType(Alias.Mail.InnerID)).Value = id;
            Command.CommandText = "SELECT " + MapColumn(Alias.Mail.ID) + " FROM " + MapTable(Alias.Objects.Mail) + " WHERE " + MapColumn(Alias.Mail.InnerID) + "=?";
            object result = Command.ExecuteScalar();
            if (result == null)
                return Guid.Empty;
            else
                return (Guid)result;
        }
        public Dictionary<string, object> Get(object id)
        {
            Dictionary<string, object> result = new Dictionary<string, object>();

            StringBuilder sql = new StringBuilder("SELECT TOP 1");
            sql.Append(" " + MapColumn(Alias.Mail.ID));
            sql.Append("," + MapColumn(Alias.Mail.InnerID));
            sql.Append("," + MapColumn(Alias.Mail.Subject));
            sql.Append("," + MapColumn(Alias.Mail.Content));
            sql.Append("," + MapColumn(Alias.Mail.IndustryID));
            sql.Append("," + MapColumn(Alias.Mail.IndustryName));
            sql.Append("," + MapColumn(Alias.Mail.RegionID));
            sql.Append("," + MapColumn(Alias.Mail.RegionName));
            sql.Append("," + MapColumn(Alias.Mail.TagID));
            sql.Append("," + MapColumn(Alias.Mail.TagName));
            sql.Append("," + MapColumn(Alias.Mail.ToCompany));
            sql.Append("," + MapColumn(Alias.Mail.Every));
            sql.Append("," + MapColumn(Alias.Mail.StartTime));
            sql.Append("," + MapColumn(Alias.Mail.LastRun));
            sql.Append("," + MapColumn(Alias.Mail.RunTimes));
            sql.Append("," + MapColumn(Alias.Mail.EndTime));
            sql.Append("," + MapColumn(Alias.Mail.LastID));
            sql.Append("," + MapColumn(Alias.Mail.LastSenderIndex));
            sql.Append("," + MapColumn(Alias.Mail.Interval));
            sql.Append("," + MapColumn(Alias.Mail.IsDeleted));
            sql.Append("," + MapColumn(Alias.Mail.CreatorID));
            sql.Append("," + MapColumn(Alias.Mail.Creator));
            sql.Append("," + MapColumn(Alias.Mail.CreateTime));
            sql.Append("," + MapColumn(Alias.Mail.UpdatorID));
            sql.Append("," + MapColumn(Alias.Mail.Updator));
            sql.Append("," + MapColumn(Alias.Mail.UpdateTime));
            sql.Append(" FROM " + MapTable(Alias.Objects.Mail));

            if (id is Guid)
            {
                Command.CommandText = sql + " WHERE " + MapColumn(Alias.Mail.ID) + "=?";

                Command.Parameters.Clear();
                Command.Parameters.Add("@" + Alias.Mail.ID, MapType(Alias.Mail.ID)).Value = id;
            }
            else
            {
                Command.CommandText = sql + " WHERE " + MapColumn(Alias.Mail.InnerID) + "=?";

                Command.Parameters.Clear();
                Command.Parameters.Add("@" + Alias.Mail.InnerID, MapType(Alias.Mail.InnerID)).Value = id;
            }

            DataReader = Command.ExecuteReader();
            if (!DataReader.HasRows)
            {
                DataReader.Close();
                return null;
            }

            DataReader.Read();
            int i = 0;
            result[Alias.Mail.ID] = DataReader[i++];
            result[Alias.Mail.InnerID] = DataReader[i++];
            result[Alias.Mail.Subject] = DataReader[i++];
            result[Alias.Mail.Content] = DataReader[i++];
            result[Alias.Mail.IndustryID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
            result[Alias.Mail.IndustryName] = DataReader[i++];
            result[Alias.Mail.RegionID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
            result[Alias.Mail.RegionName] = DataReader[i++];
            result[Alias.Mail.TagID] = DataReader[i++];
            result[Alias.Mail.TagName] = DataReader[i++];
            result[Alias.Mail.ToCompany] = DataReader[i++];
            result[Alias.Mail.Every] = DataReader[i++];
            result[Alias.Mail.StartTime] = DataReader[i++];
            result[Alias.Mail.LastRun] = DataReader[i++];
            result[Alias.Mail.RunTimes] = DataReader[i++];
            result[Alias.Mail.EndTime] = DataReader[i++];
            result[Alias.Mail.LastID] = DataReader[i++];
            result[Alias.Mail.LastSenderIndex] = DataReader[i++];
            result[Alias.Mail.Interval] = DataReader[i++];
            result[Alias.Mail.IsDeleted] = DataReader[i++];
            result[Alias.Mail.CreatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
            result[Alias.Mail.Creator] = DataReader[i++];
            result[Alias.Mail.CreateTime] = DataReader[i++];
            result[Alias.Mail.UpdatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
            result[Alias.Mail.Updator] = DataReader[i++];
            result[Alias.Mail.UpdateTime] = DataReader[i++];
            DataReader.Close();

            return result;
        }
        public void Add(Dictionary<string, object> item)
        {
            #region 设置RowLang
            item.Add(Alias.Mail.RowLang, "|" + Lang + "|");
            #endregion

            StringBuilder names = new StringBuilder();
            StringBuilder values = new StringBuilder();

            Command.Parameters.Clear();
            PrepareParameters(names, values, item);

            Command.CommandText = "INSERT INTO " + MapTable(Alias.Objects.Mail) + "(" + names + ") VALUES(" + values + ")";
            Command.ExecuteNonQuery();
        }
        public void Modify(int id, Dictionary<string, object> changes)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.Mail.InnerID, MapType(Alias.Mail.InnerID)).Value = id;

            #region 检查并设置RowLang
            Command.CommandText = "SELECT " + MapColumn(Alias.Mail.RowLang) + " FROM " + MapTable(Alias.Objects.Mail) + " WHERE " + MapColumn(Alias.Mail.InnerID) + "=?";
            string rowLang = Command.ExecuteScalar().ToString();
            if (!rowLang.Contains("|" + Lang + "|"))
                changes.Add(Alias.Mail.RowLang, rowLang + Lang + "|");
            #endregion

            StringBuilder sql = new StringBuilder("UPDATE " + MapTable(Alias.Objects.Mail) + " SET ");
            Command.Parameters.Clear();
            PrepareParameters(sql, changes);
            Command.Parameters.Add("@" + Alias.Mail.InnerID, MapType(Alias.Mail.InnerID)).Value = id;

            sql.Append(" WHERE " + MapColumn(Alias.Mail.InnerID) + "=?");

            Command.CommandText = sql.ToString();
            Command.ExecuteNonQuery();
        }
        public void Delete(int id)
        {
            Command.Parameters.Clear();
            Command.Parameters.Add("@" + Alias.Mail.InnerID, MapType(Alias.Mail.InnerID)).Value = id;

            StringBuilder sql = new StringBuilder("DELETE FROM " + MapTable(Alias.Objects.Mail) + " WHERE " + MapColumn(Alias.Mail.InnerID) + "=?");

            Command.CommandText = sql.ToString();
            Command.ExecuteNonQuery();
        }
        public DataTable List(int page, int pageSize, string condition, string sort)
        {
            DataTable result = new DataTable();
            result.Columns.Add(Alias.Mail.ID, MapCSType(Alias.Mail.ID));
            result.Columns.Add(Alias.Mail.InnerID, MapCSType(Alias.Mail.InnerID));
            result.Columns.Add(Alias.Mail.Subject, MapCSType(Alias.Mail.Subject));
            result.Columns.Add(Alias.Mail.Content, MapCSType(Alias.Mail.Content));
            result.Columns.Add(Alias.Mail.IndustryID, MapCSType(Alias.Mail.IndustryID));
            result.Columns.Add(Alias.Mail.IndustryName, MapCSType(Alias.Mail.IndustryName));
            result.Columns.Add(Alias.Mail.RegionID, MapCSType(Alias.Mail.RegionID));
            result.Columns.Add(Alias.Mail.RegionName, MapCSType(Alias.Mail.RegionName));
            result.Columns.Add(Alias.Mail.TagID, MapCSType(Alias.Mail.TagID));
            result.Columns.Add(Alias.Mail.TagName, MapCSType(Alias.Mail.TagName));
            result.Columns.Add(Alias.Mail.ToCompany, MapCSType(Alias.Mail.ToCompany));
            result.Columns.Add(Alias.Mail.Every, MapCSType(Alias.Mail.Every));
            result.Columns.Add(Alias.Mail.StartTime, MapCSType(Alias.Mail.StartTime));
            result.Columns.Add(Alias.Mail.LastRun, MapCSType(Alias.Mail.LastRun));
            result.Columns.Add(Alias.Mail.RunTimes, MapCSType(Alias.Mail.RunTimes));
            result.Columns.Add(Alias.Mail.EndTime, MapCSType(Alias.Mail.EndTime));
            result.Columns.Add(Alias.Mail.LastID, MapCSType(Alias.Mail.LastID));
            result.Columns.Add(Alias.Mail.LastSenderIndex, MapCSType(Alias.Mail.LastSenderIndex));
            result.Columns.Add(Alias.Mail.Interval, MapCSType(Alias.Mail.Interval));
            result.Columns.Add(Alias.Mail.IsDeleted, MapCSType(Alias.Mail.IsDeleted));
            result.Columns.Add(Alias.Mail.CreatorID, MapCSType(Alias.Mail.CreatorID));
            result.Columns.Add(Alias.Mail.Creator, MapCSType(Alias.Mail.Creator));
            result.Columns.Add(Alias.Mail.CreateTime, MapCSType(Alias.Mail.CreateTime));
            result.Columns.Add(Alias.Mail.UpdatorID, MapCSType(Alias.Mail.UpdatorID));
            result.Columns.Add(Alias.Mail.Updator, MapCSType(Alias.Mail.Updator));
            result.Columns.Add(Alias.Mail.UpdateTime, MapCSType(Alias.Mail.UpdateTime));

            #region 条件
            Command.Parameters.Clear();
            string parenthesis = String.Empty;
            string join = String.Empty;
            StringBuilder where = new StringBuilder();
            if (!String.IsNullOrEmpty(condition))
            {
                Match match = null;
                where.Append(" WHERE " + Alias.Mail.RowLang + " LIKE '%|" + Lang + "|%' AND ");
                where.Append("(" + condition + ")");

                ParseCondition(where, "a");

                #region IncludeSubRegion
                match = Regex.Match(where.ToString(), @"(?<=(^|\s|\())" + Alias.Mail.IncludeSubRegion + @"\s?=\s?((?<InnerID>\d+)|(?<Guid>(\{|'|'\{)?[a-fA-F0-9]{8}(-?[a-fA-F0-9]{4}){3}-?[a-fA-F0-9]{12}(\}|'|\}')?))(?=(\s|\)|$))", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    where.Remove(match.Index, match.Length);

                    object id = null;
                    if (match.Groups["InnerID"].Success)
                    {
                        id = match.Groups["InnerID"].Value;
                    }
                    else
                    {
                        string guid = match.Groups["Guid"].Value;
                        if (guid.StartsWith("{") || guid.StartsWith("'"))
                            guid = guid.Substring(1, guid.Length - 2);

                        bool isMSSql = Connection.ConnectionString.IndexOf("SQLOLEDB", StringComparison.InvariantCultureIgnoreCase) != -1;
                        if (isMSSql)
                            guid = "'" + guid + "'";
                        else
                            guid = "{" + guid + "}";

                        Command.CommandText = "SELECT " + MapColumn(Alias.Region.InnerID) + " FROM " + MapTable(Alias.Objects.Region) + " WHERE " + MapColumn(Alias.Region.ID) + "=" + guid;
                        id = Command.ExecuteScalar();
                    }

                    parenthesis += "(";
                    join += " INNER JOIN " + MapTable(Alias.Objects.Region) + " AS r ON r." + MapColumn(Alias.Region.ID) + "=a." + MapColumn(Alias.Mail.RegionID) + ")";
                    where.Insert(match.Index, "(r." + MapColumn(Alias.Region.InnerID) + "=" + id + " OR r." + MapColumn(Alias.Region.ParentChain) + " LIKE '%." + id + "' OR r." + MapColumn(Alias.Region.ParentChain) + " LIKE '%." + id + ".%')");
                }
                #endregion

                #region IncludeSubIndustry
                match = Regex.Match(where.ToString(), @"(?<=(^|\s|\())" + Alias.Mail.IncludeSubIndustry + @"\s?=\s?((?<InnerID>\d+)|(?<Guid>(\{|'|'\{)?[a-fA-F0-9]{8}(-?[a-fA-F0-9]{4}){3}-?[a-fA-F0-9]{12}(\}|'|\}')?))(?=(\s|\)|$))", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (match.Success)
                {
                    where.Remove(match.Index, match.Length);

                    object id = null;
                    if (match.Groups["InnerID"].Success)
                    {
                        id = match.Groups["InnerID"].Value;
                    }
                    else
                    {
                        string guid = match.Groups["Guid"].Value;
                        if (guid.StartsWith("{") || guid.StartsWith("'"))
                            guid = guid.Substring(1, guid.Length - 2);

                        bool isMSSql = Connection.ConnectionString.IndexOf("SQLOLEDB", StringComparison.InvariantCultureIgnoreCase) != -1;
                        if (isMSSql)
                            guid = "'" + guid + "'";
                        else
                            guid = "{" + guid + "}";

                        Command.CommandText = "SELECT " + MapColumn(Alias.Industry.InnerID) + " FROM " + MapTable(Alias.Objects.Industry) + " WHERE " + MapColumn(Alias.Industry.ID) + "=" + guid;
                        id = Command.ExecuteScalar();
                    }

                    parenthesis += "(";
                    join += " INNER JOIN " + MapTable(Alias.Objects.Industry) + " AS i ON i." + MapColumn(Alias.Industry.ID) + "=a." + MapColumn(Alias.Mail.IndustryID) + ")";
                    where.Insert(match.Index, "(i." + MapColumn(Alias.Industry.InnerID) + "=" + id + " OR i." + MapColumn(Alias.Industry.ParentChain) + " LIKE '%." + id + "' OR i." + MapColumn(Alias.Industry.ParentChain) + " LIKE '%." + id + ".%')");
                }
                #endregion
            }
            else
            {
                where.Append(" WHERE a." + MapColumn(Alias.Mail.RowLang) + " LIKE '%|" + Lang + "|%'");
            }
            #endregion

            #region 排序
            if (!String.IsNullOrEmpty(sort))
                sort = " ORDER BY " + ParseSort(sort, "a");
            else
                sort = " ORDER BY a." + MapColumn(Alias.Mail.InnerID) + " DESC";
            #endregion

            #region 构造SQL语句
            StringBuilder sql = new StringBuilder("SELECT");
            if (page > 0 && pageSize > 0)
                sql.Append(" TOP " + (page * pageSize));
            sql.Append(" a." + MapColumn(Alias.Mail.ID));
            sql.Append(",a." + MapColumn(Alias.Mail.InnerID));
            sql.Append(",a." + MapColumn(Alias.Mail.Subject));
            sql.Append(",a." + MapColumn(Alias.Mail.Content));
            sql.Append(",a." + MapColumn(Alias.Mail.IndustryID));
            sql.Append(",a." + MapColumn(Alias.Mail.IndustryName));
            sql.Append(",a." + MapColumn(Alias.Mail.RegionID));
            sql.Append(",a." + MapColumn(Alias.Mail.RegionName));
            sql.Append(",a." + MapColumn(Alias.Mail.TagID));
            sql.Append(",a." + MapColumn(Alias.Mail.TagName));
            sql.Append(",a." + MapColumn(Alias.Mail.ToCompany));
            sql.Append(",a." + MapColumn(Alias.Mail.Every));
            sql.Append(",a." + MapColumn(Alias.Mail.StartTime));
            sql.Append(",a." + MapColumn(Alias.Mail.LastRun));
            sql.Append(",a." + MapColumn(Alias.Mail.RunTimes));
            sql.Append(",a." + MapColumn(Alias.Mail.EndTime));
            sql.Append(",a." + MapColumn(Alias.Mail.LastID));
            sql.Append(",a." + MapColumn(Alias.Mail.LastSenderIndex));
            sql.Append(",a." + MapColumn(Alias.Mail.Interval));
            sql.Append(",a." + MapColumn(Alias.Mail.IsDeleted));
            sql.Append(",a." + MapColumn(Alias.Mail.CreatorID));
            sql.Append(",a." + MapColumn(Alias.Mail.Creator));
            sql.Append(",a." + MapColumn(Alias.Mail.CreateTime));
            sql.Append(",a." + MapColumn(Alias.Mail.UpdatorID));
            sql.Append(",a." + MapColumn(Alias.Mail.Updator));
            sql.Append(",a." + MapColumn(Alias.Mail.UpdateTime));
            sql.Append(" FROM " + parenthesis + MapTable(Alias.Objects.Mail) + " AS a");
            sql.Append(join + where + sort);
            Command.CommandText = sql.ToString();
            #endregion

            #region 执行SQL语句并获取记录
            int curIndex = 0, rowIndex = 0;
            int startIndex = (page - 1) * pageSize;
            DataReader = Command.ExecuteReader();
            while (DataReader.Read())
            {
                if (pageSize != -1)
                {
                    if (curIndex < startIndex)
                    {
                        curIndex++;
                        continue;
                    }

                    if (rowIndex == pageSize)
                        break;
                }

                DataRow row = result.NewRow();
                int i = 0;
                row[Alias.Mail.ID] = DataReader[i++];
                row[Alias.Mail.InnerID] = DataReader[i++];
                row[Alias.Mail.Subject] = DataReader[i++];
                row[Alias.Mail.Content] = DataReader[i++];
                row[Alias.Mail.IndustryID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
                row[Alias.Mail.IndustryName] = DataReader[i++];
                row[Alias.Mail.RegionID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
                row[Alias.Mail.RegionName] = DataReader[i++];
                row[Alias.Mail.TagID] = DataReader[i++];
                row[Alias.Mail.TagName] = DataReader[i++];
                row[Alias.Mail.ToCompany] = DataReader[i++];
                row[Alias.Mail.Every] = DataReader[i++];
                row[Alias.Mail.StartTime] = DataReader[i++];
                row[Alias.Mail.LastRun] = DataReader[i++];
                row[Alias.Mail.RunTimes] = DataReader[i++];
                row[Alias.Mail.EndTime] = DataReader[i++];
                row[Alias.Mail.LastID] = DataReader[i++];
                row[Alias.Mail.LastSenderIndex] = DataReader[i++];
                row[Alias.Mail.Interval] = DataReader[i++];
                row[Alias.Mail.IsDeleted] = DataReader[i++];
                row[Alias.Mail.CreatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
                row[Alias.Mail.Creator] = DataReader[i++];
                row[Alias.Mail.CreateTime] = DataReader[i++];
                row[Alias.Mail.UpdatorID] = DataReader[i] == DBNull.Value ? Guid.Empty : DataReader[i]; i++;
                row[Alias.Mail.Updator] = DataReader[i++];
                row[Alias.Mail.UpdateTime] = DataReader[i++];
                result.Rows.Add(row);

                rowIndex++;
            }
            DataReader.Close();
            #endregion

            return result;
        }
        public int GetRecordCount(string condition)
        {
            #region 条件
            Command.Parameters.Clear();
            string parenthesis = String.Empty;
            string join = String.Empty;
            StringBuilder where = new StringBuilder();
            if (!String.IsNullOrEmpty(condition))
            {
                where.Append(" WHERE " + Alias.Mail.RowLang + " LIKE '%|" + Lang + "|%' AND ");
                where.Append("(" + condition + ")");

                ParseCondition(where, "a");
            }
            else
            {
                where.Append(" WHERE a." + MapColumn(Alias.Mail.RowLang) + " LIKE '%|" + Lang + "|%'");
            }
            #endregion

            Command.CommandText = "SELECT COUNT(*) FROM " + parenthesis + MapTable(Alias.Objects.Mail) + " AS a" + join + where;
            return Convert.ToInt32(Command.ExecuteScalar());
        }
    }
}
